package main.kotlin.singlePage

import java.io.File
import java.io.RandomAccessFile
import java.io.ByteArrayInputStream
import net.dongliu.requests.*


class ImageDownloader {

    var proxy: List<String> = listOf()
        set(value) {
            if (value.size == 2) {
                field = value
            }
        }


    /* 判断输出文件是否存在，文件大小是否一致 */
    private fun checkImg(outFile: String): Long {
        var position  = 0L
        val file = File(outFile)
        if(file.exists()) {
            position = file.length()
        }

        return position
    }

    /*
    借助与FileOutStream下载文件
    */
    fun download(url: String, outFile: String, stdout: Boolean = true) {

        if (stdout) {
            println("Downloading: $url")
        }

        val content: ByteArray
        val input: ByteArrayInputStream

        when (this.proxy.size) {
            2 -> {
                content = Requests.get(url)
                        .socksTimeout(30_000)
                        .connectTimeout(30_000)
                        .proxy(Proxies.socksProxy(this.proxy.first(), this.proxy.last().toInt()))
                        .send()
                        .readToBytes()
            }
            else -> {
                content = Requests.get(url)
                        .socksTimeout(30_000)
                        .connectTimeout(30_000)
                        .send()
                        .readToBytes()
            }
        }

        input = ByteArrayInputStream(content)

        // 检查文件是否存在，或者文件大小
        val position: Long = checkImg(outFile)

        val writer = RandomAccessFile(outFile, "rw")

        input.skip(position)
        writer.seek(position)

        // 读取所有文件
        val byte = input.readBytes()
        writer.write(byte)

        writer.close()
        input.close()
    }
}